package com.antoco.operation.bigscreen.controller.modelcontroller.impl;

import com.antoco.operation.bigscreen.commons.annotation.IsSensorExist;
import com.antoco.operation.bigscreen.controller.modelcontroller.intf.SensorController;
import com.antoco.operation.bigscreen.model.dto.SensorDTO;
import com.antoco.operation.bigscreen.model.dto.SensorParamDTO;
import com.antoco.operation.bigscreen.model.entity.Sensor;
import com.antoco.operation.bigscreen.mapper.SensorMapper;
import com.antoco.operation.bigscreen.mapper.SensorParamMapper;
import com.antoco.operation.bigscreen.service.WebSocketServer;
import com.antoco.operation.bigscreen.service.autogeneration.intf.SensorService;
import net.sf.json.JSONObject;
import com.antoco.operation.bigscreen.service.ChannelDataService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@RequestMapping("/model/sensor")
@RestController
@Validated
public class SensorControllerImpl implements SensorController {

    @Autowired
    private SensorService sensorService;

    @Autowired
    private SensorMapper sensorMapper;

    @Autowired
    private SensorParamMapper sensorParamMapper;

    @Autowired
    private ChannelDataService channelDataService;

    @Autowired
    private WebSocketServer webSocketServer;

    @Override
    @PostMapping
    @ResponseStatus(HttpStatus.CREATED)
    public SensorParamDTO save(@Validated @RequestBody SensorParamDTO sensorDTO) {
        Sensor sensor = sensorParamMapper.asEntity(sensorDTO);
        sensorService.save(sensor);
        channelDataService.pushAllLists(this.getClass().getName());
        return sensorDTO;
    }

    @Override
    @GetMapping("/{id}")
    public SensorDTO findById(@PathVariable("id") Long id) {
        Sensor sensor = sensorService.findById(id).orElse(null);
        return sensorMapper.asDTO(sensor);
    }

    @Override
    @DeleteMapping("/{id}")
    public void delete(@PathVariable("id") Long id) {
        sensorService.deleteById(id);
        channelDataService.pushAllLists(this.getClass().getName());
    }

    @Override
    @GetMapping
    public List<SensorDTO> list() {
        return sensorMapper.asDTOList(sensorService.findAll());
    }

    @Override
    @GetMapping("/page-query")
    public Page<SensorDTO> pageQuery(Pageable pageable) {
        Page<Sensor> sensorPage = sensorService.findAll(pageable);
        List<SensorDTO> dtoList = sensorPage
                .stream()
                .map(sensorMapper::asDTO).collect(Collectors.toList());
        return new PageImpl<>(dtoList, pageable, sensorPage.getTotalElements());
    }

    @Override
    @PutMapping("/{id}")
    public SensorDTO update(@Validated @RequestBody SensorParamDTO sensorDTO, @PathVariable("id") @IsSensorExist Long id) {

        // 更新传感器
        Sensor sensor = sensorParamMapper.asEntity(sensorDTO);
        sensor.setId(id);
        sensorService.update(sensor, id);

        // 获取最新的传感器记录并推送
        Optional<Sensor> newSensorOptional = sensorService.findById(id);
        Sensor newSensor = newSensorOptional.get();
        SensorDTO newSensorDTO = sensorMapper.asDTO(newSensor);

        List<SensorDTO> list = new ArrayList<SensorDTO>();
        list.add(newSensorDTO);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("sensor", list);
        JSONObject jsonObjectEnd = new JSONObject();
        jsonObjectEnd.put("channel", "SENSO@".concat(String.valueOf(newSensorDTO.getId())));
        jsonObjectEnd.put("data", jsonObject);
        try {
            webSocketServer.send2Channel("SENSO", jsonObjectEnd.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return newSensorDTO;
    }
}